package com.vnp.cooking;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.utils.PreferenceHelper;

import android.opengl.Visibility;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class LoginWithFacebookActivity extends Activity {
	
	
	WebView webviewLoginFB;
	ProgressBar progressBar;
	String urllogin = "http://anuong.net/api/login/facebook";
	String urllogout = "http://anuong.net/api/user/logout";
	PreferenceHelper preferenceHelper;
	String access = "http://anuong.net/api/login?access_code=";
	boolean isLoaded= false;
	private static final String SCREEN_LABEL = "Dang nhap voi fb screen";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_with_facebook);
		
		preferenceHelper = new PreferenceHelper(this);

		webviewLoginFB= (WebView) findViewById(R.id.webloginFB);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		progressBar.setVisibility(ProgressBar.GONE);
		
		webviewLoginFB.getSettings().setJavaScriptEnabled(true);
		webviewLoginFB.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
                if (progress == 100) {
                	progressBar.setVisibility(ProgressBar.INVISIBLE);
                    progressBar.setProgress(0);
                } else {
                	progressBar.setVisibility(ProgressBar.VISIBLE);
                }
            }
        });
		

		webviewLoginFB.setWebViewClient(new MyWebViewClient());
		webviewLoginFB.loadUrl(urllogin);
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
		
	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}
	
	
	private class MyWebViewClient extends WebViewClient {
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, final String url) {
	    	if(url.startsWith(access)&&(isLoaded == false)){
				Log.i("DATA", url);
				isLoaded = true;
			       if (url.startsWith(access)) {
			    	   webviewLoginFB.setVisibility(View.GONE);
						Thread tr = new Thread(){

							@Override
							public void run() {
								String str = "";
						        HttpResponse response;
						        HttpClient myClient = new DefaultHttpClient();
						        HttpPost myConnection = new HttpPost(url);
						         Log.i("DATA", "--------------1");
						        try {
						            response = myClient.execute(myConnection);
						            Log.i("DATA", "--------------2");
						            str = EntityUtils.toString(response.getEntity(), "UTF-8");
						            Log.i("DATA", "DATA CHUA PASER: "+str);
						        } catch (ClientProtocolException e) {
						            e.printStackTrace();
						        } catch (IOException e) {
						            e.printStackTrace();
						        }
						        

			             try{
					            JSONObject jo = new JSONObject(str);
					            
					            JSONArray datas = null;
					            JSONObject data = jo.optJSONObject("data");
					            

					            if (data == null) {
					            	datas = jo.optJSONArray("data");
					            	
					            	Intent loginIntent = new Intent(LoginWithFacebookActivity.this, LoginWithFacebookActivity.class);
					            	finish();
					                loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					                startActivity(loginIntent);
					            } else {
					            	Log.i("DATA", "DATA LOGIN: "+ data.toString());
					            	String userID = data.getString("id");
					            	Log.i("DATA", "ID nguoi dung: "+ userID);
					            	preferenceHelper.setID(userID);
					            	preferenceHelper.setUserInfoName(data.getString("name"));
					            	preferenceHelper.setUserEmail(data.getString("email"));
					            	preferenceHelper.setUserURLAvatar(data.getString("avatar"));
					            	preferenceHelper.setUserBirth(data.getString("dob"));
					            	preferenceHelper.setUserGender(data.getString("gender"));
					            	preferenceHelper.setUserAbout(data.getString("about"));
					            	preferenceHelper.setUserName(data.getString("username"));
					            	preferenceHelper.setUserCity(data.getInt("city_id"));
					            	preferenceHelper.setUserLevelName(data.getString("level_name"));
					            	preferenceHelper.setSettingsComment(data.getInt("notification_comment"));
					            	preferenceHelper.setSettingsLike(data.getInt("notification_like"));
					            	gotoMain();
								}
					            
					             
					        } catch ( JSONException e) {
					            e.printStackTrace();                
					        }
							}
							
						};
						tr.start();

					}
			} else {
				webviewLoginFB.loadUrl(url);
			}
	        return true;
	    }
	    
	    


		@Override
		public void onPageStarted(WebView view, final String url, Bitmap favicon) {
			
		}
	    
	}
	
	
	void gotoMain() {
		Intent t = new Intent(LoginWithFacebookActivity.this, MainActivity.class);
		finish();
		t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(t);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		webviewLoginFB.loadUrl(urllogout);
	}


}
